//
//  HMHomeViewController.swift
//  WymanWeibo
//
//  Created by wyman on 16/4/8.
//  Copyright © 2016年 wyman. All rights reserved.
//

import UIKit

import SVPullToRefresh

import SVProgressHUD
class HMHomeViewController: HMBaseTableViewController {

    private let ReseIdentifier = "SSID"
    //微博模型
    var statuses: [HMStatus]?{
        didSet{
        HMPrint("总的微博数据:\(statuses?.count)")
            self.tableView.reloadData()
        
        }
    
    }
    private lazy var pullDownRefreshControl:HMPullDownRefreshControlNor = HMPullDownRefreshControlNor()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if !HMUserAccountViewModel.shareInstance.userLogin  {
            return
        }
        
        
        setupNavigationBar()

        
//navigationController?.navigationBar.translucent = false

        tableView.addSubview(pullDownRefreshControl)
        
        //设置闭包
        pullDownRefreshControl.pullDownRefreshHandler = {() -> () in
        
            
            
            
            self.loadNewStatu()
            
        }
    
        pullDownRefreshControl.startRefreshing()
        
        tableView.addInfiniteScrollingWithActionHandler { 
            HMPrint("上啦加载数据")
            self.loadMoreStatus()
        }
        
        self.tableView.registerClass(HMStatusCell.self, forCellReuseIdentifier: self.ReseIdentifier)

          //设置预估行高
        tableView.rowHeight = UITableViewAutomaticDimension;
//        tableView.estimatedRowHeight = 200
        tableView.separatorStyle = .None;
        //加载数据
        
        
//        HMStatusViewModel.sharedInstance.loadStatus(0, max_id: 0) { (statuses, error) in
//      
//            if error != nil{
//            HMPrint("获取数据失败了:\(error)")
//            return
//            }
//
//            self.statuses = statuses
////            HMPrint(statuses)
//            self.tableView.reloadData()
//        }
        
        
    }
    
    //上啦加载
    private func loadMoreStatus() {
        // 获取id最小的微博
        let max_id = self.statuses?.last?.id ?? 0
        
        // 一条微博数据都没有,就不去上拉加载更多数据
        if max_id == 0 {
            HMPrint("没有微博数据,不去上拉加载更多数据")
            return
        }
        
        // 加载比 max_id 还小得微博
        HMStatusViewModel.sharedInstance.loadStatus(0, max_id: max_id) { (statuses, error) -> () in
            // 让刷新控件结束刷新
            self.tableView.infiniteScrollingView.stopAnimating()
            
            if error != nil {
                HMPrint("上拉加载更多微博数据失败了: \(error)")
                return
            }
            
            let count = statuses?.count ?? 0
            
            HMPrint("加载更多的数据条数: \(count)")
            
            if count == 0 {
                // 没有加载更多的数据了
                HMPrint("没有加载更多的数据了")
                SVProgressHUD.showErrorWithStatus("没有加载更多的数据了")
                return
            }
            
            
            
            // 拼接数据,老得微博数据拼接到现有数据的后面
            let s = self.statuses! + statuses!
            self.statuses = s
        }
    }

    private func loadNewStatu(){
    //获取最大ID
        let since_id = self.statuses?.first?.id ?? 0
        
        HMStatusViewModel.sharedInstance.loadStatus(since_id, max_id: 0) { (statuses, error) in
            
            self.pullDownRefreshControl.endRefresh()
            
//            self.showTipLabel((statuses?.count)!)

            if error != nil{
            HMPrint("获取微博数据出错")
                return;
            }
            
            let count = statuses?.count ?? 0
            HMPrint("加载了多少数据\(count)")
            
            if since_id != 0 {
                // 用户手动拖拽,显示下拉刷新的条数
                self.showTipLabel(count)
            }
            
            if count == 0 {
            HMPrint("没有加载到数据")
                if since_id == 0{
                
                }
                return
            }
            
            if since_id == 0{
            self.statuses = statuses
            
            }else{
            
            let s = statuses!+self.statuses!
                
                self.statuses = s
            }
            
        }
        
}
   private func setupNavigationBar(){
    
    
    navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", target: self, action: Selector("didClickPerson:"))
    
     navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: Selector("didClickQRCode:"))
    
       let title = HMUserAccountViewModel.shareInstance.userAccount?.screen_name ?? "无名"
    //设置title按钮
    let titleBtn = HMHomeTitleButton(title: title)
    
    titleBtn.addTarget(self, action: Selector("didClickTitleBtn:"), forControlEvents: .TouchUpInside)
    
    navigationItem.titleView = titleBtn
    }
    @objc private func didClickTitleBtn(button: HMHomeTitleButton){
        
        HMPrint("点了了home左边里面的按钮")
        
        //点击的话  三角型向上
        button.selected = !button.selected
        HMPrint("\(button.selected)")
        
        UIView.animateWithDuration(HMDefautlAnimDuration) {
            button.imageView?.transform = button.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI)) : CGAffineTransformIdentity
        }
    }
    // MARK: - Table view data source
    @objc private func didClickPerson(button: UIButton){
    
      
    }
    
    @objc private func didClickQRCode(button: UIBarButtonItem){
         HMPrint("点了了home右边里面的按钮")
    }
    
    



//显示下拉数据提示
private func showTipLabel(count: Int){
  
    tipLabel.text = count == 0 ? "没有新的微博数据" : "下拉刷新\(count)条微博"

    let y = -(UIApplication.sharedApplication().statusBarFrame.height+TipLabelHeight)
    
    tipLabel.frame = CGRect(x: 0, y: y, width: UIScreen.mainScreen().bounds.width, height: TipLabelHeight)
    
    tipLabel.text = count == 0 ? "没有新的微博数据" : "下拉刷新\(count)条微博"
    
    if let keys = tipLabel.layer.animationKeys(){
    HMPrint("正在执行动画,keys: \(keys)")
        return
        
    
    }

    //label动画
    UIView.animateWithDuration(HMDefautlAnimDuration, animations: { 
        self.tipLabel.frame = CGRect(x: 0, y: TipLabelHeight, width: UIScreen.mainScreen().bounds.width, height: TipLabelHeight)
        }) { (_) in
            UIView.animateWithDuration(1, delay: 0.5, options: [], animations: {
                self.tipLabel.frame = CGRect(x: 0, y: -(UIApplication.sharedApplication().statusBarFrame.height + TipLabelHeight), width: UIScreen.mainScreen().bounds.width, height: TipLabelHeight)
                }, completion: { (_) in
//                    self.tipLabel.removeFromSuperview()
            })
            
    }
}

    private lazy var tipLabel: UILabel = {
    
    let label = UILabel(fontSize: 14, textColor: UIColor.whiteColor())
    
    label.backgroundColor = UIColor.orangeColor()
    label.textAlignment = .Center
    self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)

    return label
    }()


}



extension HMHomeViewController{
    
    //返回行高
   override  func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    //获取模型
    let staus = self.statuses![indexPath.row]
    
    
    if staus.rowHeight != nil {
    
//    HMPrint("使用缓存的行高\(staus.rowHeight)")
    return staus.rowHeight!
    }
    
    //没有的话,自己算行高
    
    let cell = tableView.dequeueReusableCellWithIdentifier(ReseIdentifier) as! HMStatusCell

    //模型给cell
    cell.status = staus
    
    //获取高度
    let height = cell.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
    
    staus.rowHeight = height
    
//    HMPrint("计算行高\(height)")
    
    return height
    
    }
    
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.statuses?.count ?? 0
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//        let cell = tableView.dequeueReusableCellWithIdentifier(ReseIdentifier) as! HMStatusCell
        let cell = tableView.dequeueReusableCellWithIdentifier(ReseIdentifier, forIndexPath: indexPath)as! HMStatusCell

//        cell.textLabel?.text = self.statuses![indexPath.row].text
        cell.status = self.statuses![indexPath.row]
        
//        HMPrint("Cell")
        return cell
    }
//    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
//        HMPrint("RowHeigt")
//        
//        super.tableView(tableView, heightForRowAtIndexPath:indexPath )
//    }
    
    override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return false
    }

}
